<?php

#namespace humhub\modules\space\controllers;
namespace humhub\modules\api\controllers;

use Yii;
use yii\helpers\Url;
use yii\web\HttpException;
use humhub\modules\user\models\User;
use humhub\modules\user\widgets\UserPicker;
use humhub\modules\space\models\Space;
use humhub\models\Setting;
use humhub\modules\space\models\Membership;
use humhub\modules\space\models\forms\RequestMembershipForm;
use humhub\modules\user\widgets\UserListBox;
use humhub\modules\post\models\Post;

use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;

/**
 * 搜索被邀请用户列表, 邀请用户加入Space板块, 获取Space的成员列表, 显示/隐藏DashBoard的Space内容, 加入Space, 申请加入Space, 申请的用户列表, 处理申请
 */
class SpaceMembershipController extends Base2Controller
{

    /**
     * @inheritdoc
     */
    public function init(){
        $_GET['sguid'] = Yii::$app->request->get('s');
        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function behaviors(){
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                //QueryParamAuth::className(),
                HttpBearerAuth::className(),
            ],
        ];

        $behaviors['acl'] = [
            'class' => \humhub\components\behaviors\AccessControl::className(),
        ];

        return $behaviors;
    }

    /**
     * @inheritdoc
     */
    public function actions(){
        $actions = parent::actions();
        unset($actions['index'], $actions['view'], $actions['delete'], $actions['update'], $actions['create']);
        return $actions;
    }

    /**
     * 搜索被邀请用户列表
     *
     * GET /api/space-membership/search-invite?s=[sguid]&keyword=[keyword]
     *
     * get.s 板块Space的guid
     *
     * get.keywrod 搜索关键字
     *
     * @return array 用户列表,包含:guid, displayname, image, 等...
     */
    public function actionSearchInvite(){
        $space = $this->getSpace();
        if (!$space->isMember()) {
            throw new HttpException(404, Yii::t('SpaceModule.controllers_SpaceController', 'This action is only available for workspace members!'));
        }
        if( ! Yii::$app->request->get('keyword') ){
            throw new HttpException(400, '关键字不能为空');
        }

        return UserPicker::filter([
                    'query' => $space->getNonMembershipUser(),
                    'keyword' => Yii::$app->request->get('keyword'),
                    'fillUser' => true
        ]);
    }

    /**
     * 加入Space板块 (Requests Membership for this Space)
     *
     * POST /api/space-membership/request-membership?s=[guid]
     *
     * get.s 板块Space的guid
     *
     * @return boolean 如加入失败,返回错误信息; 当code=401时,表明此板块可以申请加入.
     */
    public function actionRequestMembership(){
        $this->forcePostRequest();
        $space = $this->getSpace();

        if( $space->created_by == Yii::$app->user->id ){
            throw new HttpException(500, '无效的申请.');
        }
        if (!$space->canJoin(Yii::$app->user->id))
            throw new HttpException(500, Yii::t('SpaceModule.controllers_SpaceController', '申请失败.'));

        if ($space->join_policy == Space::JOIN_POLICY_APPLICATION) {
            // Redirect to Membership Request Form
            throw new HttpException(500, '当前板块需要申请加入', 401);
        }

        $space->addMember(Yii::$app->user->id);

        return true;
    }

    /**
     * 申请(请求)成为会员, 如果该Space可以直接加入直接调用'加入Space板块(api/space-membership/request-membership)'接口即可
     *
     * POST /api/space-membership/request-membership-form?s=[guid]
     *
     * get.s 板块Space的guid
     *
     * post.RequestMembershipForm[message] 请求内容
     *
     * @return boolean
     */
    public function actionRequestMembershipForm(){
        $space = $this->getSpace();

        // Check if we have already some sort of membership
        //if (Yii::$app->user->isGuest || $space->getMembership(Yii::$app->user->id) != null) {
        //    throw new HttpException(500, Yii::t('SpaceModule.controllers_SpaceController', 'Could not request membership!'));
        //}
        if (Yii::$app->user->isGuest) {
            throw new HttpException(500, Yii::t('SpaceModule.controllers_SpaceController', 'Could not request membership!'));
        }
        if ($space->getMembership(Yii::$app->user->id) != null) {
            return true;
        }

        $model = new RequestMembershipForm();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $space->requestMembership(Yii::$app->user->id, $model->message);
            return true;
        }

        Yii::$app->params['res-success'] = false;
        return $model->getErrors();
    }

    /**
     * 退出Space板块 / 取消Space的申请 / 拒绝别人的邀请 (Revokes Membership for this workspace)
     *
     * POST /api/space-membership/revoke-membership?s=[guid]
     *
     * get.s 板块Space的guid
     *
     * @return boolean
     */
    public function actionRevokeMembership(){
        $this->forcePostRequest();
        $space = $this->getSpace();

        if ($space->isSpaceOwner()) {
            throw new HttpException(500, Yii::t('SpaceModule.controllers_SpaceController', 'As owner you cannot revoke your membership!'));
        } elseif (!$space->canLeave()) {
            throw new HttpException(500, Yii::t('SpaceModule.controllers_SpaceController', 'Sorry, you are not allowed to leave this space!'));
        }

        $space->removeMember();

        return true;
    }

    /**
     * 邀请用户加入Space板块
     *
     * POST /api/space-membership/invite?s=[guid]
     *
     * get.s 板块Space的guid
     *
     * post.InviteForm[invite]  被邀请用户guid列表,每个guid以逗号','结尾
     */
    public function actionInvite(){
        $space = $this->getSpace();

        // Check Permissions to Invite
        if (!$space->canInvite()) {
            throw new HttpException(403, 'Access denied - You cannot invite members!');
        }

        $canInviteExternal = Yii::$app->getModule('user')->settings->get('auth.internalUsersCanInvite');


        $model = new \humhub\modules\space\models\forms\InviteForm();
        $model->space = $space;

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {

            $statusInvite = false;

            // Invite existing members
            foreach ($model->getInvites() as $user) {
                $space->inviteMember($user->id, Yii::$app->user->id);
                $statusInvite = $space->getMembership($user->id)->status;
            }

            // Invite non existing members
            if ($canInviteExternal) {
                foreach ($model->getInvitesExternal() as $email) {
                }
            }

            return true;
            //return $this->renderAjax('statusInvite', [
            //            'status' => $statusInvite,
            //            'canInviteExternal' => $canInviteExternal
            //]);
        }

        Yii::$app->params['res-success'] = false;
        return false;
        //return $this->renderAjax('invite', array('model' => $model, 'space' => $space, 'canInviteExternal' => $canInviteExternal));
    }

    /**
     * 接受被邀请加入某Space
     *
     * POST /api/space-membership/invite-accept?s=[guid]
     *
     * get.s 板块Space的guid
     *
     * @return boolean
     */
    public function actionInviteAccept(){
        $this->forcePostRequest();
        $space = $this->getSpace();

        // Load Pending Membership
        $membership = $space->getMembership();
        if ($membership == null) {
            throw new HttpException(404, Yii::t('SpaceModule.controllers_SpaceController', 'There is no pending invite!'));
        }

        // Check there are really an Invite
        if ($membership->status == Membership::STATUS_INVITED) {
            $space->addMember(Yii::$app->user->id);
        }

        return true;
    }

    /**
     * 获取Space的成员请求加入列表
     *
     * GET /api/space-membership/invite-list?s=[guid]
     *
     * get.s 空间guid
     *
     * @return array displayname:姓名, guid用户guid, img用户头像, message请求信息
     */
    public function actionInviteList(){
        // Only visible for admins
        if (!$this->space->isAdmin()) {
            throw new HttpException(403, 'Access denied.');
        }

        //$query->count()
        $pagination = new \yii\data\Pagination([
            'defaultPageSize' => 20,
            'validatePage' => false,
        ]);

        $applicants = $this->space->getApplicants()->offset($pagination->offset)->limit($pagination->limit)->all();
        $list = [];
        foreach($applicants AS $membership){
            $user = $membership->user;
            $u['displayname'] = $user->displayName;
            $u['guid'] = $user->guid;
            $u['img'] = $user->getProfileImage()->getUrl();
            $u['message'] = $membership->request_message;
            $list[] = $u;
        }
        return $list;
    }

    /**
     * 拒绝新成员(加入Space)的申请 
     *
     * POST /api/space-membership/reject-applicant?s=[guid]
     *
     * get.s 板块Space的guid
     *
     * post.userGuid
     *
     * @return boolean 
     */
    public function actionRejectApplicant(){
        // Only visible for admins
        if (!$this->space->isAdmin()) {
            throw new HttpException(403, 'Access denied.');
        }
        $this->forcePostRequest();

        $space = $this->getSpace();
        $userGuid = Yii::$app->request->post('userGuid');
        $user = User::findOne(['guid' => $userGuid]);

        if ($user != null) {
            $space->removeMember($user->id);
        }
        return true;
    }

    /**
     * 接受新成员(加入Space)的申请 
     *
     * POST /api/space-membership/approve-applicant?s=[guid]
     *
     * get.s 板块Space的guid
     *
     * post.userGuid
     *
     * @return boolean 
     */
    public function actionApproveApplicant(){
        // Only visible for admins
        if (!$this->space->isAdmin()) {
            throw new HttpException(403, 'Access denied.');
        }
        $this->forcePostRequest();

        $space = $this->getSpace();
        $userGuid = Yii::$app->request->post('userGuid');
        $user = User::findOne(['guid' => $userGuid]);

        if ($user != null) {
            $membership = $space->getMembership($user->id);
            if ($membership != null && $membership->status == Membership::STATUS_APPLICANT) {
                $space->addMember($user->id);
            }
            return true;
        }
        throw new HttpException(400, '操作失败');
    }

    /**
     * 显示/隐藏Space内容到Dashboard (Show/Hide posts on dashboard)
     *
     * POST /api/space-membership/switch-dashboard-display?s=[guid]
     *
     * get.s 板块Space的guid
     *
     * post.show 显示=1, 隐藏=0
     *
     * @return boolean
     */
    public function actionSwitchDashboardDisplay(){
        $_GET['show'] = Yii::$app->request->post('show');
        $this->forcePostRequest();
        $space = $this->getSpace();

        // Load Pending Membership
        $membership = $space->getMembership();
        if ($membership == null) {
            throw new HttpException(404, 'Membership not found!');
        }

        if (Yii::$app->request->get('show') == 0) {
            $membership->show_at_dashboard = 0;
        } else {
            $membership->show_at_dashboard = 1;
        }
        $membership->save();

        return true;
    }

    /**
     * 获取某板块Space的成员列表
     *
     * GET /api/space-membership/members-list?s=[guid]
     *
     * get.guid : 板块guid
     *
     * @return array guid用户guid, profileimage:头像, displayname:姓名, title:个人Title
     */
    public function actionMembersList(){
        $query = Membership::getSpaceMembersQuery($this->getSpace());

        //$query->count()
        $pagination = new \yii\data\Pagination([
            'defaultPageSize' => 20,
            'validatePage' => false,
        ]);

        $users = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();

        $u = [];
        foreach($users AS $user){
            $uone['guid']           = $user->guid;
            $uone['profileimage']   = $user->getProfileImage()->getUrl();
            $uone['displayname']    = $user->displayName;
            $uone['title']          = $user->profile->title;
            $uone['follow']         = \humhub\modules\api\models\Follow::getFollow($user, Yii::$app->user->id);//$this->getUser()->id
            $uone['countFollowers'] = $user->getFollowerCount(); //被关注
            $u[] = $uone;
        }
        return $u;
    }
}
?>
